<?php

class PlayerModel extends BpfModel
{
  public function checkLogin()
  {
    return !empty($_SESSION['player_id']) ? $_SESSION['player_id'] : false;
  }

  public function createPlayer($from)
  {
    return Player::create($from);
  }

  public function getPlayer($playerid, $type = 'players.player_id')
  {
    if (empty($playerid)) { return false; }
    static $list = [];
    $cacheid = $playerid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $player = $mysqlModel->getSqlBuilder()
        ->from('players')
        ->where($type, $playerid)
        ->query()->row('Player');
      $list[$cacheid] = $player;
    }
    return $list[$cacheid];
  }

  public function getStore($storeid, $type = 'stores.store_id')
  {
    static $list = [];
    $cacheid = $storeid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $player = $mysqlModel->getSqlBuilder()
        ->from('stores')
        ->select('stores.*, players.nickname')
        ->join('players', 'players.player_id = stores.store_id')
        ->where($type, $storeid)
        ->query()->row('Store');
      $list[$cacheid] = $player;
    }
    return $list[$cacheid];
  }

  private function _setPlayersFilter($query, $filter)
  {
    $query->from('players');
    if (isset($filter)) {
      if (!empty($filter['search'])) {
        $search = '%' . $filter['search'] . '%';
        $query->WhereGroupStart();
        $query->orWhere('players.nickname LIKE', $search);
        $query->whereGroupEnd();
      }
      if (isset($filter['flowers_items gte']) && is_numeric($filter['flowers_items gte'])) {
        $query->Where('players.flowers_items >', $filter['flowers_items gte']);
      }
      if (isset($filter['opengift']) && is_numeric($filter['opengift'])) {
        $query->Where('players.opengift', $filter['opengift']);
      }
    }
  }

  public function getPlayersCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->select('COUNT(0)');
    $this->_setPlayersFilter($query, $filter);
    return $query->query()->field();
  }

  public function getPlayersList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('players.*')
        ->limitPage($rows, $page);
    $this->_setPlayersFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('players.created asc');
    } if (isset($filter['flowers_history DESC']) ) {
      $query->orderby('players.flowers_history DESC');
    } else {
      $query->orderby('players.created desc');
    }
    return $query->query()->all('Player');
  }

  public function createComment($from)
  {
    return Comment::create($from);
  }

  public function getComment($commentid, $type = 'comments.comment_id')
  {
    static $list = [];
    $cacheid = $commentid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $comment = $mysqlModel->getSqlBuilder()
        ->from('comments')
        ->where($type, $commentid)
        ->query()->row('Comment');
      $list[$cacheid] = $comment;
    }
    return $list[$cacheid];
  }

  private function _setCommentsFilter($query, $filter)
  {
    $query->from('comments');
    if (isset($filter)) {
      if (!empty($filter['search'])) {
        $search = '%' . $filter['search'] . '%';
        $query->WhereGroupStart();
        $query->orWhere('comments.comment LIKE', $search);
        $query->whereGroupEnd();
      }
      if (isset($filter['player_id']) && is_numeric($filter['player_id'])) {
        $query->Where('comments.player_id', $filter['player_id']);
      }
      if (isset($filter['store_id']) && is_numeric($filter['store_id'])) {
        $query->Where('comments.store_id', $filter['store_id']);
      }
    }
  }

  public function getCommentsCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->select('COUNT(0)');
    $this->_setCommentsFilter($query, $filter);
    return $query->query()->field();
  }

  public function getCommentsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('comments.*')
        ->limitPage($rows, $page);
    $this->_setCommentsFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('comments.created asc');
    } else {
      $query->orderby('comments.created desc');
    }
    return $query->query()->all('Comment');
  }

  public function createLuckydraw($from)
  {
    return Luckydraw::create($from);
  }

  public function getLuckydraw($luckydrawid, $type = 'luckydraws.luckydraw_id')
  {
    static $list = [];
    $cacheid = $luckydrawid . $type;
    if (empty($list[$cacheid])) {
      $mysqlModel = $this->getModel('mysql');
      $luckydraw = $mysqlModel->getSqlBuilder()
        ->from('luckydraws')
        ->where($type, $luckydrawid)
        ->query()->row('Luckydraw');
      $list[$cacheid] = $luckydraw;
    }
    return $list[$cacheid];
  }

  private function _setLuckydrawsFilter($query, $filter)
  {
    $query->from('luckydraws')->join('players', 'players.player_id = luckydraws.player_id');
    if (isset($filter)) {
      if (isset($filter['player_id']) && is_numeric($filter['player_id'])) {
        $query->Where('luckydraws.player_id', $filter['player_id']);
      }
      if (!empty($filter['date'])) {
        $query->Where('luckydraws.date', $filter['date']);
      }
      if (isset($filter['created gte']) && is_numeric($filter['created gte'])) {
        $query->Where('luckydraws.created >=', $filter['created gte']);
      }
      if (isset($filter['created lte']) && is_numeric($filter['created lte'])) {
        $query->Where('luckydraws.created <=', $filter['created gte']);
      }
    }
  }

  public function getLuckydrawsCount($filter = null, $distinct = false)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder();
    if ($distinct) {
      $query->select('COUNT(DISTINCT luckydraws.player_id)');
    } else {
      $query->select('COUNT(0)');
    }
    $this->_setLuckydrawsFilter($query, $filter);
    return $query->query()->field();
  }

  public function getLuckydrawsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('luckydraws.*')
        ->select('players.nickname, players.headimgurl')
        ->limitPage($rows, $page);
    $this->_setLuckydrawsFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('luckydraws.created asc');
    } else {
      $query->orderby('luckydraws.created desc');
    }
    return $query->query()->all('Luckydraw');
  }

  //签到记录
  private function _setPlayerSginsFilter($query, $filter)
  {
    $query->from('players_signs');
    if (isset($filter)) {
      if (isset($filter['player_id']) && is_numeric($filter['player_id'])) {
        $query->Where('players_signs.player_id', $filter['player_id']);
      }
      if (!empty($filter['date'])) {
        $query->Where('players_signs.date', $filter['date']);
      }
    }
  }

  public function getPlayerSginsCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder();
    $query->select('COUNT(0)');
    $this->_setPlayerSginsFilter($query, $filter);
    return $query->query()->field();
  }

  public function getPlayerSginsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->select('players_signs.*')
        ->limitPage($rows, $page);
    $this->_setPlayerSginsFilter($query, $filter);
    if (isset($filter['created ASC']) ) {
      $query->orderby('players_signs.created asc');
    } else {
      $query->orderby('players_signs.created desc');
    }
    if (!empty($filter['allWithKeyDate'])) {
      return $query->query()->allWithKey('date');
    }
    return $query->query()->all();
  }

  //鲜花记录
  private function _setFlowerLogsFilter($query, $filter)
  {
    $query->from('players_flowers_logs');
    if (isset($filter)) {
      if (!empty($filter['search'])) {
        $search = '%' . $filter['search'] . '%';
        $query->WhereGroupStart();
        $query->whereGroupEnd();
      }
      if (!empty($filter['player_id'])) {
        $query->Where('players_flowers_logs.player_id', $filter['player_id']);
      }
    }
  }

  public function getFlowerLogsList($filter = null, $page = 1, $rows = 10)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
        ->limitPage($rows, $page);
    $this->_setFlowerLogsFilter($query, $filter);
    $query->orderby('players_flowers_logs._id DESC');
    return $query->query()->all();
  }

  public function getFlowerLogsCount($filter = null)
  {
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->select('COUNT(0)');
    $this->_setFlowerLogsFilter($query, $filter);
    return $query->query()->field();
  }

}

class Player extends BpfObject
{

  public static function create($form)
  {
    $playerid = BpfObject::getModel('mysql')->getSqlBuilder()->insert('players', [
      'openid' => trim($form['openid']),
      'parent_id' => intval($form['parent_id'] ?? 0),
      'nickname' => trim($form['nickname'] ?? ''),
      'headimgurl' => trim($form['headimgurl'] ?? ''),
      'created' => REQUEST_TIME,
      'updated' => REQUEST_TIME
    ])->query()->insertId();
    return BpfObject::getModel('player')->getPlayer($playerid);
  }

  public function getId()
  {
    return $this->player_id;
  }

  public function update()
  {
    return $this->getModel('mysql')->getSqlBuilder()->update('players', [
      'phone' => trim($this->phone),
      'parent_id' => intval($this->parent_id),
      'has_store' => intval($this->has_store),
      'realname' => trim($this->realname),
      'address' => trim($this->address),
      'nickname' => trim($this->nickname),
      'headimgurl' => trim($this->headimgurl),
      'country' => trim($this->country),
      'province' => trim($this->province),
      'city' => trim($this->city),
      'opengift' => intval($this->opengift),
      'sigin_last_date' => trim($this->sigin_last_date),
      'sigin_seriate_times' => intval($this->sigin_seriate_times),
      'sigin_seriate_max_times' => max(intval($this->sigin_seriate_times), intval($this->sigin_seriate_max_times)),
      'updated' => REQUEST_TIME
    ], ['player_id' => $this->player_id])->query()->affectedRows();
  }

  public function login()
  {
    $_SESSION['player_id'] = $this->player_id;
    //计算上次登陆的收益
    return true;
  }

  public function hasStore()
  {
     return $this->has_store == '1';
  }

  public function openStore()
  {
    if ($this->hasStore()) {
      return false;
    }
    $this->has_store = 1;
    $store = new Store();
    $store->store_id = $this->player_id;
    $store->monkey_disappear_time = REQUEST_TIME;
    if ($store->update() && $this->update()) {
      return $store;
    };
    return false;
  }

  public function getStore()
  {
    $playerModel = $this->getModel('player');
    return $playerModel->getStore($this->player_id);
  }

  public function chageFlowers($op, $flowers, $message, $extend = '')
  {
    $mysqlModel = $this->getModel('mysql');
    $flowers = floatval($flowers);
    if (!$flowers) { return false; }
    if (!$this->hasStore()) { return false; }
    $sql = join(' ', [
      'UPDATE `players` SET',
       '`flowers` = `flowers` + ' . $flowers . ',',
       '`flowers_history` = IF(' . $flowers .' > 0 , `flowers_history` + ' . $flowers . ', `flowers_history`)',
      'WHERE `player_id` = ' . $this->player_id . ' AND `flowers` >= ' . -$flowers
    ]);
    $affecte = $mysqlModel->query($sql)->affectedRows();
    if ($affecte) {
      $this->flowers = $this->flowers + $flowers;
      $message = $mysqlModel->escape($message);
      $extend = $mysqlModel->escape($extend);
      $op = $mysqlModel->escape($op);
      $sql = join(' ', [
        "INSERT INTO `players_flowers_logs` (`player_id`, `op`, `nflowers`, `flowers`, `oflowers`,  `message`, `created`, `extend`)",
        '(SELECT',
          "{$this->player_id} AS `player_id`, '{$op}' AS `op`,",
          "`flowers` AS `nflowers`, {$flowers} AS `flowers`,",
          "(`flowers` - {$flowers}) AS `oflowers`, '{$message}' AS `message`,",
           REQUEST_TIME . " AS `created`, '{$extend}' AS `extend`",
        "FROM `players` WHERE `players`.`player_id` = {$this->player_id})"
      ]);
      $mysqlModel->query($sql);
    }
    return $affecte;
  }

  public function hudong($op, $message, $extend = '')
  {
    //
    $cacheid = join('-', ['hudong', date('Ymd', REQUEST_TIME), $this->player_id]);
    $redisModel = $this->getModel('redis');
    $configModel = $this->getModel('config');
    $limitHudongFlowers = intval('0' . $configModel->get('flowers.hudong.limit', 150));
    $toadyHudongFlowers = intval($redisModel->__call('get', [ $cacheid ]));
    if ($toadyHudongFlowers >= $limitHudongFlowers) {
      return false;
    }
    $hudongFlowers = intval('0' . $configModel->get('flowers.hudong', 5));
    if ($result = $this->chageFlowers($op, $hudongFlowers, $message, $extend)) {
      if ($toadyHudongFlowers) {
        $redisModel->__call('INCRBY', [ $cacheid, $hudongFlowers]);
      } else {
        //做一天的缓存
        $redisModel->__call('SETEX', [ $cacheid, 86400, $hudongFlowers]);
      }
    }
    return $result;
  }

  public function getFlowerLogsList($filter = null, $page = 1, $rows = 10)
  {
    return $this->getModel('player')->getFlowerLogsList(['player_id' => $this->player_id], $page, $rows);
  }

  public function getFlowerLogsCount($filter = null)
  {
    return $this->getModel('player')->getFlowerLogsCount(['player_id' => $this->player_id]);
  }

  public function exchange($giftid)
  {
    if (!($gift = $this->getModel('gift')->getGift($giftid))) { return false; }
    if ($gift->flowers > $this->flowers) { return false; }
    if ($gift->status != Gift::IS_ONLINE) { return false; }
    if ($gift->type == Gift::IS_PRODUCT && $gift->amount <= 0) { return false; }
    if ($gift->type == Gift::IS_PRODUCT && empty($this->address)) {return false;}

    //扣除积分
    if ($this->chageFlowers('礼品兑换', -$gift->flowers, $gift->name, $gift->gift_id)) {
      $result = $gift->createPlayerGift([
        'player_id' => $this->player_id,
        'data' => [
          'address' => $this->address, 'phone' => $this->phone, 'realname' => $this->realname,
        ]
      ]);
      //清除掉用户的留资
      if ($result) {
        $this->address = '';
        $this->phone = '';
        $this->realname = '';
        $this->update();
      }
      return $result;
    }
    return false;
  }

  public function allowLuckydraw($date, &$error = '')
  {
    //判断积分够不够
    if ( $this->flowers < intval(0 . $this->getModel('config')->get('flowers.luckydraw.join', 50)) )  {
      $error = '您的鲜花不足';
      return false;
    }
    //判断今日是否参与过抽奖
    return $this->getModel('player')->getLuckydrawsCount([
      'date' => $date, 'player_id' => $this->player_id
    ]) == 0;
  }

  public function joinLuckydraw(&$error = '')
  {
    $date = date('Ymd', REQUEST_TIME);
    if (!$this->allowLuckydraw($date)) {
      return false;
    }
    $playerModel = $this->getModel('player');
    $luckydraw = $playerModel->createLuckydraw(['date' => $date, 'player_id' => $this->player_id]);
    if ($luckydraw) {
      $configModel = $this->getModel('config');
      $flowersOfLuckydrawJoin = intval('0' . $configModel->get('flowers.luckydraw.join', 50));
      //扣除积分，
      if ($this->chageFlowers('抽奖池', -$flowersOfLuckydrawJoin, "{$luckydraw->date}参与抽奖", $luckydraw->luckydraw_id)) {
        //积分池自增
        $configModel->incr('luckydraw.pond', $flowersOfLuckydrawJoin);
        return true;
      } else {
        $luckydraw->delete();
        $error = '扣除鲜花失败';
        return false;
      }
    } else {
      $error = '参与失败！！';
    }
    return false;
  }

  public function addComment($message, $storeid)
  {
    $playerModel = $this->getModel('player');
    $store = $playerModel->getPlayer($storeid);
    $comment = $playerModel->createComment([
      'store_id' => $store->player_id,
      'player_id' => $this->player_id,
      'comment' => $message,
      'data' => [
        'tonickname' => $store->nickname, 'toheadimgurl' => $store->headimgurl,
        'fromonickname' => $this->nickname, 'fromheadimgurl' => $this->headimgurl,
      ]
    ]);
    return $comment;
  }

  public function pickLikeComments($commentids = [])
  {
    $mysqlModel = $this->getModel('mysql');
    return $mysqlModel->getSqlBuilder()
      ->select('comment_id')
      ->from('comments_likes')
      ->where('comment_id in', $commentids)->where('player_id', $this->player_id)->query()->column();
  }

  public function bindParent($parentid)
  {
    if (empty($this->parent_id)
      && $parentid != $this->player_id
      && ($parent = $this->getModel('player')->getPlayer($parentid))
      && $parent->parent_id != $this->player_id) {
      $this->parent_id = $parent->player_id;
        return $this->update();
    }
    return false;
  }

  public function sgin()
  {
    $date = date('Ymd', REQUEST_TIME);
    $affected = BpfObject::getModel('mysql')->getSqlBuilder()->insert('players_signs', [
      'player_id' => intval($this->player_id),
      'date' => $date,
      'created' => REQUEST_TIME,
    ], true, true, ['created'])->query()->affectedRows();
    if ($affected) {
      if ($this->sigin_last_date == date('Ymd', REQUEST_TIME - 86400)) {
        $this->sigin_seriate_times++;
      } else {
        $this->sigin_seriate_times = 1;
      }
      $this->sigin_last_date = $date;
      $this->update();
    }
    return $affected;
  }

  public function getSginRecordsList($filter = null, $page = 1, $rows = 10)
  {
    return $this->getModel('player')->getPlayerSginsList([
      'player_id' => $this->player_id,
      'allWithKeyDate' => isset($filter['allWithKeyDate'])
    ], $page, $rows);
  }

  public function like($friend_id, $isfriend = false)
  {
    if ($friend = $this->getModel('player')->getPlayer($friend_id)) {
      $mysqlModel = $this->getModel('mysql');
      $sql = $mysqlModel->getSqlBuilder()->insert('player_friends', [
        ['player_id' => $this->player_id, 'friend_id'=> $this->player_id, 'like' => 0, 'created' => REQUEST_TIME],
        ['player_id' => $this->player_id, 'friend_id'=> $friend->player_id, 'like' => $isfriend ? 0: 1, 'created' => REQUEST_TIME],
        ['player_id' => $friend->player_id, 'friend_id'=> $this->player_id, 'like' => 0, 'created' => REQUEST_TIME],
      ])->getSql() . ' ON DUPLICATE KEY UPDATE `like` = VALUES(`like`) OR `like`';
      return $mysqlModel->query($sql)->affectedRows();
    }
    return false;
  }

  public function isLike($friend_id)
  {
    return boolval($this->getModel('mysql')->getSqlBuilder()->from('player_friends')->select('`like`')
      ->where('player_id', $this->player_id)->where('friend_id', $friend_id)->query()->field());
  }

  public function settleItemFlower()
  {
    if ($this->flowers_items < 1) { return false; }
    $itemflowers = intval($this->flowers_items);
    if ($this->getModel('mysql')->query('UPDATE `players` SET `flowers_items` = `flowers_items` - ? WHERE `flowers_items` >= ? AND `player_id` = ?', [
      $itemflowers, $itemflowers, $this->player_id
    ])->affectedRows()) {
      //商品收益
      $this->chageFlowers('商品收益', $itemflowers, '有顾客来购买啦');
    };
  }

  public function getChildrenFlowers($filter = [], $page, $rows = 10)
  {
    $date = date('Ymd', REQUEST_TIME - 86400);
    $mysqlModel = $this->getModel('mysql');
    $query = $mysqlModel->getSqlBuilder()
      ->from('players')
      ->select(' IF(players_children_flowers.status = 1, 0, players_children_flowers.flowers)  AS flowers, players_children_flowers.status')
      ->select('players.nickname, players.headimgurl, players.player_id')
      ->join('players_children_flowers', 'players.player_id = players_children_flowers.child_id', 'LEFT')
      ->where('players.parent_id', $this->player_id);
    $query->WhereGroupStart();
    $query->orWhere('players_children_flowers.date', $date);
    $query->orWhere('players_children_flowers.date', NULL);
    $query->whereGroupEnd();
    $result = [];
    foreach ($query->limitPage($rows, $page)->query()->all() as $data) {
      $data->flowers = intval($data->flowers);
      $data->status = $data->flowers ? intval($data->status): 1;
      $data->date = $date;
      $result[] = $data;
    }
    return $result;
    // $mysqlModel = $this->getModel('mysql');
    // $query = $mysqlModel->getSqlBuilder()
    //   ->select('players_children_flowers.child_id AS player_id')
    //   ->select('players_children_flowers.flowers AS flowers')
    //   ->select('players_children_flowers.date AS date')
    //   ->select('players.nickname, players.headimgurl')
    //   ->from('players_children_flowers')
    //   ->join('players', 'players.player_id = players_children_flowers.child_id')
    //   ->where('players_children_flowers.player_id', $this->player_id)
    //   ->limitPage($rows, $page);
    // if (isset($filter['date'])) {
    //   $query->where('players_children_flowers.date', $filter['date']);
    // }
    // if (isset($filter['status']) && is_numeric($filter['status'])) {
    //   $query->where('players_children_flowers.status', $filter['status']);
    // }
    // return $query->query()->all();
  }

  public function getItemFlowersIncomes()
  {
    return $this->getModel('mysql')->query('SELECT FLOOR(SUM(`flowers`)) FROM `players_flowers_logs` WHERE `op` = ? AND `player_id` = ? AND `created` BETWEEN ? AND ?', [
      '商品收益', $this->player_id, $this->access, REQUEST_TIME
    ])->field(0) ?? 0;
  }

  public function reapChildrenFlowers()
  {
    //只收获昨日的鲜花
    $date = date('Ymd', REQUEST_TIME - 86400);
    $mysqlModel = $this->getModel('mysql');
    if ($mysqlModel->query('UPDATE `players_children_flowers` SET `status` = 1, `updated` = ? WHERE `player_id` = ? AND `date` = ? AND `status` = 0', [
      REQUEST_TIME, $this->player_id, $date
    ])->affectedRows()) {
      $flowers = $mysqlModel->query('SELECT sum(`flowers`) FROM `players_children_flowers` WHERE `player_id` = ? AND `updated` = ? AND `date` = ?', [
        $this->player_id, REQUEST_TIME, $date
      ])->field();
      if ($flowers) {
        $this->chageFlowers('合伙人分成', $flowers, '[' . $date . ']合伙人鲜花');
        return $flowers;
      }
    }
    return false;
  }

  public function visitorTo($player_id)
  {
    //插入成功做缓存
    $cacheid = join('-', ['visitor', $this->player_id, $player_id]);
    $redisModel = $this->getModel('redis');
    if ($redisModel->__call('get', [$cacheid])) { return true; }
    $this->getModel('mysql')->query('INSERT IGNORE INTO `access_logs` (`player_id`, `visitor_id`, `week`) VALUES (?, ? , ?)', [
      $player_id, $this->player_id, date('YW', REQUEST_TIME)
    ]);
    $redisModel->__call('SETEX', [$cacheid, 604800, 1]);
    return true;
  }

  public function getVisitorWeekCount($week = '')
  {
    return $this->getModel('mysql')->query('SELECT COUNT(0) FROM `access_logs` WHERE `player_id` = ? AND `week` = ?', [
      $this->player_id, $week
    ])->field();
  }

  public function getflowersWeekCount($week = '')
  {
    return $this->getModel('mysql')->query('SELECT FLOOR(SUM(`flowers`)) FROM `players_flowers_statistics` WHERE `player_id` = ? AND `week` = ? ', [
      $this->player_id, $week
    ])->field() ?? 0;
  }

  public function access()
  {
    $this->getModel('mysql')->query('UPDATE `players` SET `access` = ? WHERE `player_id` = ? ', [
      REQUEST_TIME, $this->player_id
    ]);
  }

}

class Comment extends BpfObject
{
  private function __fetch()
  {
    $this->data = json_decode($this->data, true) ?? [];
  }

  public static function create($form)
  {
    $commentid = BpfObject::getModel('mysql')->getSqlBuilder()->insert('comments', [
      'store_id' => intval($form['store_id'] ?? 0),
      'player_id' => intval($form['player_id'] ?? 0),
      'comment' => trim($form['comment']),
      'data' => json_encode($form['data']),
      'created' => REQUEST_TIME,
    ])->query()->insertId();
    return BpfObject::getModel('player')->getComment($commentid);
  }

  public function getId()
  {
    return $this->comment_id;
  }

  public function delete()
  {
    return $this->getModel('mysql')->getSqlBuilder()->delete('comments', [
      'comment_id' => $this->comment_id
    ])->query()->affectedRows();
  }

  public function likeBy($player_id)
  {
    $cacheid = join('-', ['beLike', $this->comment_id, $player_id]);
    $redisModel = $this->getModel('redis');
    if ($redisModel->__call('get', [$cacheid])) { return true; }
    $mysqlModel = $this->getModel('mysql');
    if ($mysqlModel->query('INSERT IGNORE INTO `comments_likes` (`comment_id`, `player_id`, `created`) VALUES (?, ? , ?)', [
        $this->comment_id, $player_id, REQUEST_TIME
      ])->affectedRows()) {
      $mysqlModel->query('UPDATE `comments` SET `likes` = `likes` + 1 WHERE `comment_id` = ?', [ $this->comment_id ]);
    }
    $redisModel->__call('SET', [$cacheid, 1]);
    return true;
  }

}

class Luckydraw extends BpfObject {
  public static function create($form)
  {
    $luckydrawid = BpfObject::getModel('mysql')->getSqlBuilder()->insert('luckydraws', [
      'player_id' => intval($form['player_id'] ?? 0),
      'date' => trim($form['date']),
      'created' => REQUEST_TIME,
    ])->query()->insertId();
    return BpfObject::getModel('player')->getLuckydraw($luckydrawid);
  }

  public function getId()
  {
    return $this->luckydraw_id;
  }

  public function delete()
  {
    return $this->getModel('mysql')->getSqlBuilder()->delete('luckydraws', [
      'luckydraw_id' => $this->luckydraw_id
    ])->query()->affectedRows();
  }

}

class Store extends BpfObject {

  protected function __fetch()
  {
    $this->data = json_decode($this->data, true) ?? [];
  }

  public function getId()
  {
    return $this->store_id;
  }

  public function update()
  {
    $updated = [
      'store_id' => intval($this->store_id), 'created' => REQUEST_TIME,
      'items' => $this->isItemLocked() ? 3: 4
    ];
    !empty($this->data) && ($updated['data'] = json_encode($this->data));
    isset($this->monkey_appear) && ($updated['monkey_appear'] = boolval($this->monkey_appear));
    !empty($this->monkey_disappear_time) && ($updated['monkey_disappear_time'] = intval($this->monkey_disappear_time));
    return $this->getModel('mysql')->getSqlBuilder()->insert('stores', $updated, true, true, [ 'created' ])->query()->affectedRows();
  }

  public function isItemLocked()
  {
    return ($this->items ?? 3) == 4 ? false: true;
  }

  public function unLockItem()
  {
    if (!$this->isItemLocked()) { return false; }
    $this->items = 4;
    return $this->update();
  }

  public function getCommentsList($filter = null, $page = 1, $rows = 10)
  {
    return $this->getModel('player')->getCommentsList([
      'store_id' => $this->store_id,
    ], $page, $rows);
  }

  public function getItems()
  {
    return $this->getModel('mysql')->getSqlBuilder()
    ->from('stores_items')
    ->select('items.*')
    ->join('items', 'stores_items.item_id = items.item_id')
    ->where('stores_items.store_id', $this->store_id)
    ->query()->all();
  }

  public function upItems($itemids = [])
  {
    $mysqlModel = $this->getModel('mysql');
    $mysqlModel->getSqlBuilder()->delete('stores_items', [
      'store_id' => $this->store_id
    ])->query();
    $now = REQUEST_TIME;
    $sql= 'INSERT INTO `stores_items` (`item_id`, `store_id`, `expire_in`)' .
      " SELECT `item_id`, {$this->store_id} AS `store_id`, {$now} + (`lifetime` * 60) AS `expire_in` FROM `items`" .
      'WHERE `item_id` IN ? ';
    return $mysqlModel->query($sql, [$itemids])->affectedRows();
  }

  public function appearMonkey()
  {
    $this->monkey_appear = true;
    return $this->update();
  }

  public function disappearMonkey()
  {
    if (!$this->monkey_appear) { return false; }
    $this->monkey_appear = false;
    $this->monkey_disappear_time = REQUEST_TIME;
    return $this->update();
  }

}